package com.shawn.leetcode.array.two;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSum {

	public List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		if(nums == null && nums.length < 3){
			return result;
		}

		Arrays.sort(nums);
		int n = nums.length;
		for (int i = 0; i < n; i++) {
			if(nums[i] > 0){
				break;
			}

			if(i > 0 && nums[i] == nums[i - 1]){
				continue;
			}

			int head = i + 1;
			int tail = n - 1;
			int value = 0 - nums[i];

			while (head < tail){
				int data = nums[head] + nums[tail];
				if(data == value){
					result.add(Arrays.asList(nums[i],nums[head],nums[tail]));
					while (head < tail && nums[tail] == nums[tail - 1]){
						tail--;
					}
					while (head < tail && nums[head] == nums[head + 1]){
						head++;
					}
					tail--;
					head++;
				}else if(data < value){
					head++;
				}else if(data > value){
					tail--;
				}
			}
		}

		return result;
	}

}
